package com.shopx.base.aspect;

import com.microsoft.schemas.office.visio.x2012.main.IconType;
import com.shopx.base.anno.ShopxCheckParamAnno;
import com.shopx.base.exception.OriginException;
import com.shopx.core.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.HashMap;
import java.util.Map;

@Aspect
@Component
@Slf4j
public class ShopxCheckParamAspect {
    @Before("@annotation(anno)")
    public void before(JoinPoint joinPoint, ShopxCheckParamAnno anno) {
        try {
            Map<String, Object> map = this.convert(joinPoint.getArgs()[0]);
            if(map==null || map.isEmpty()){
                return;
            }
            if(map.get("order")==null){
                return;
            }
            String order = map.get("order").toString();
            if(StringUtil.isEmpty(order)){
                return;
            }
            String keys[] = new String[]{"delete","drop","truncate","insert","update",";"};
            for(String s :keys){
                if(order.indexOf(s)>-1){
                    throw new OriginException("参数解析错误");
                }
            }
        }catch (Exception e){
            throw new OriginException("参数解析错误");
        }
    }

    private Map<String, Object> convert(Object obj) throws IllegalAccessException {
        Map<String, Object> map = new HashMap<>();
        Class<?> clazz = obj.getClass();
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true);
            map.put(field.getName(), field.get(obj));
        }
        return map;
    }
}
